package cn.ven.service;

import cn.ven.entity.MyUser;
import cn.ven.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService,UserDetailsService {

    @Autowired(required = false)
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public List<MyUser> selectAllUser() {
        return userMapper.selectAll();
    }

    @Override
    public void addUser(MyUser user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRole("B");
        user.setClosed(1);
        user.setFocusNum(0);
        user.setFocusedNum(0);
       userMapper.insert(user);
    }

    @Override
    public MyUser findById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public MyUser findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public List<MyUser> selectAllByClosedAndRole(int closed, String role) {
        LambdaQueryWrapper<MyUser> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(MyUser::getClosed,closed);
        queryWrapper.eq(MyUser::getRole,role);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public void delUser(int uid) {
        LambdaQueryWrapper<MyUser> queryWrapper =new LambdaQueryWrapper();
        queryWrapper.eq(MyUser::getId,uid);
        userMapper.delete(queryWrapper);
    }

    @Override
    public void updateUser(MyUser user) {
        userMapper.updateById(user);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser user = userMapper.findByUsername(username);
        return user;
    }
}
